/*
 * api调用基础类
 */
import {
    Config
} from './config';
import {Utils} from './util';
import {
    Token
} from './token';
class Base {
    static baseRequestUrl = Config.restUrl;
    constructor() {
        // this.baseRequestUrl = Config.restUrl;
    }

    static request(params, noRefetch = false) {
        return new Promise((resolve, reject) => {

            // 判断是否设置全路径参数，如果设置了则不使用合并根路径与子路径的方式
            let url = Base.baseRequestUrl + params.url;

            if (params.fullurl) {
                url = params.fullurl
            }
            if (!params.type) {
                //默认使用Get方式调用api
                params.type = 'GET';
            }

            wx.request({
                "url": url,
                "method": params.type,
                "data": params.data || {},
                "header": params.header || {
                    'content-type': 'application/json',
                    'Authorization': 'JWT '+ wx.getStorageSync('token').access
                },
                "responseType": params.responseType || 'text',
                success: (res) => {
                    
                    if (res.data.code == 200) {
                        resolve(res.data.data)
                    } else {
                        if (res.data.code in {"201":"","401":"","402":"","403":""}) {
                            if (!noRefetch) {
                                Base._refetch(params);
                            }
                        } else {
                            reject(res.data);
                        }
                    }

                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }

    static _refetch(params) {
        Token.refreshToken().then(res => {
            return Base.request(params, true);
        })
    }
}

export {
    Base
};